<template>
  <view id="account_login" class="user_account account_login">
    <view class="container">
      <view class="custom-1"></view>
      <view class="custom-2"></view>
      <view class="custom-3"></view>
      <view class="custom-4"><text>玉林师范学院迎新系统</text></view>
      <view class="custom-5"></view>

      <view class="login-wrapper">
        <view class="input-content">
          <view class="input-item">
            <view class="input-item-icon">
              <view class="tn-icon-my-lack"></view>
            </view>
            <input
                type="text"
                v-model="form.username"
                placeholder="请输入用户名"
                maxlength="16"
                data-key="username"
            />
          </view>
          <view class="input-item">
            <view class="input-item-icon">
              <view class="tn-icon-lock"></view>
            </view>
            <input
                v-model="form.password"
                placeholder="请输入密码"
                placeholder-class="input-empty"
                maxlength="20"
                :password="!showPassword"
                data-key="password"
                @confirm="login"
            />
            <view class="input-item-icon">
              <view
                  @click="showPassword = !showPassword"
                  :class="[showPassword ? 'tn-icon-eye' : 'tn-icon-eye-hide']"
              >
              </view>
            </view>
          </view>
        </view>
        <button class="confirm-btn" @click="login" :disabled="logining">登录</button>
        <view class="forget-section">
          <view @click="$navTo('/pagesB/account/forgot')">忘记密码?</view>
        </view>
                  		<view class="register-section">
			还没有账号?
			<view @click="$navTo('/pagesB/account/register')" class="text">马上注册</view>
		</view>
        <view class="author-wrap" style="width: 100%; display: flex; justify-content: center">
          <!-- #ifdef MP-WEIXIN -->
          <view class="author">
            <button class="author-weixin" @click="getUserInfo"></button>
          </view>
          <!-- #endif -->
          <!-- #ifdef APP-VUE || H5 -->
          <view class="author">
            <button class="author-weixin" @click="weixin"></button>
          </view>
          <!-- #endif -->
        </view>
      </view>
    </view>

  </view>
</template>

<script>
  import mixin from '@/libs/mixins/page.js';
  import {loginApi} from '@/api/login.js';
  import wx_open from "@/libs/wx_open.json";

  export default {
    mixins: [mixin],
    data() {
      return {
        logining: false,
		allow_user: [
			'管理员'
				,"学生用户"
					,"教师用户"
									],
        form: {
          username: '',
          password: '',
        },
        rules: {
          username: {
            rules: [
              {
                required: true,
                errorMessage: '请输入用户名',
              },
              {
                minLength: 5,
                maxLength: 16,
                errorMessage: '用户名长度在 {minLength} 到 {maxLength} 个字符',
              },
            ],
          },
          password: {
            rules: [
              {
                required: true,
                errorMessage: '请输入密码',
              },
              {
                minLength: 5,
                maxLength: 16,
                errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
              },
            ],
          },
        },
        showPassword: false,
      };
    },
    onLoad() {
      console.log(this.$u.route);
    },
    methods: {
      closePopup() {
        this.logining = false;
      },
      login() {
        this.logining = true;
        let form = Object.assign({}, this.form);
        // 检查是否存在临时openid (微信账号关联)
        const temp_openid = uni.getStorageSync('temp_openid');
        if (temp_openid) {
          // 如果存在临时openid，则进行账号关联
          form.open_id = temp_openid;
          // 关联成功后清除临时openid
          uni.removeStorageSync('temp_openid');
          
          this.$post(
            '~/api/user/open_id_login?',
            form,
            (res) => {
              if (res.result && res.result.obj) {
                let user = res.result.obj;
                if(this.allow_user.includes(user.user_group)){
                  // 缓存token
                  this.$u.vuex('token', user.token);
                  // 存储用户信息
                  this.$u.vuex('userInfo', user);
                  // 设置权限集
                  this.$u.vuex('userGroup', user.user_group);
                  // 前往首页
                  uni.switchTab({
                    url: '/pages/index/index',
                  });
                  this.$toast("微信账号绑定成功", 'success');
                  console.log('---登录成功---');
                }else{
                  this.$toast("您的账号不支持在用户端登录！", 'error');
                }
              } else if (res.error) {
                this.$toast(res.error.message, 'error');
              }
              this.logining = false;
            }
          );
          return;
        }
        
        // 常规登录
        loginApi(form)
          .then((res) => {
            if (res.result && res.result.obj) {
              let user = res.result.obj;
			  if(this.allow_user.includes(user.user_group)){
				  				  // 缓存token
				  this.$u.vuex('token', user.token);
				  // 存储用户信息
				  this.$u.vuex('userInfo', user);
				  // 设置权限集
				  this.$u.vuex('userGroup', user.user_group);
				  // 前往首页
				  uni.switchTab({
				    url: '/pages/index/index',
				  });
				  console.log('---登录成功---');
			  }else{
				  this.$toast("您的账号不支持在用户端登录！", 'error');
			  }
              
            } else if (res.error) {
              this.$toast(res.error.message, 'error');
            }
          })
          .finally(() => {
            this.logining = false;
          });
      },
      /**
       * 手动重置表单
       */
      resetForm() {
        this.$refs.form.resetFields();
      },
      // #ifdef APP-VUE || H5
      // 三个授权组件地址
      // Tencent(){
      // 	uni.navigateTo({
      // 		url:'../authorization/authorization?id=1'
      // 	})
      // },
      weixin() {
        this.$nav('/pagesB/authorization/authorization-weixin?id=2');
      },
      // weibo(){
      // 	uni.navigateTo({
      // 		url:'../authorization/authorization-weibo?id=3'
      // 	})
      // }
      // #endif
      // #ifdef MP-WEIXIN
      getUserInfo() {
        uni.showLoading({
          // 展示加载框
          title: '加载中',
        });
        
        // 获取用户授权信息
        uni.getUserProfile({
          desc: '登录后可同步数据',
          success: async (obj) => {
            console.log('完整的微信用户信息:', obj.userInfo); // 输出完整用户信息调试
            
            // 检查昵称是否为空或显示为"微信用户"
            if (!obj.userInfo.nickName || obj.userInfo.nickName === '微信用户') {
              // 尝试使用其他信息作为昵称
              this.nickName = '微信用户' + Math.floor(Math.random() * 10000); // 添加随机数以区分不同用户
            } else {
              this.nickName = obj.userInfo.nickName;
            }
            
            // 临时存储微信头像URL
            const wxAvatarUrl = obj.userInfo.avatarUrl;
            
            // 执行登录流程
            this.doWechatLogin(wxAvatarUrl);
          },
          fail: (err) => {
            console.error('获取用户信息失败:', err);
            uni.showToast({
              title: '授权已取消',
              icon: 'error',
              mask: true,
            });
          },
          complete: () => {
            // 隐藏loading
            uni.hideLoading();
          },
        });
      },
      
      // 执行微信登录
      doWechatLogin(wxAvatarUrl) {
        // 获取微信登录凭证
        uni.login({
          provider: 'weixin',
          success: (res) => {
            console.log('微信登录凭证:', res);
            if (res.errMsg == 'login:ok') {
              // 保存code
              const code = res.code;
              
              // 获取openid
              const ps = {
                appid: wx_open.appid,
                secret: wx_open.secret,
                js_code: code,
                grant_type: 'authorization_code',
              };
              
              this.$get('https://api.weixin.qq.com/sns/jscode2session', ps, (response) => {
                console.log('openid响应:', response);
                if (response.openid) {
                  const openid = response.openid;
                  
                  // 准备请求参数
                  const loginParams = {
                    open_id: openid,
                    nickname: this.nickName,
                    avatar: '' // 初始设置为空
                  };
                  
                  // 尝试下载头像并上传
                  if (wxAvatarUrl) {
                    this.tryUploadAvatar(wxAvatarUrl, loginParams, openid);
                  } else {
                    // 无头像直接登录
                    this.finishWechatLogin(loginParams);
                  }
                } else {
                  uni.showToast({
                    icon: 'none',
                    title: '获取用户凭证失败！',
                  });
                }
              });
            }
          },
          fail: (err) => {
            console.error('微信登录失败:', err);
            uni.showToast({
              icon: 'none',
              title: '微信登录失败！',
            });
          }
        });
      },
      
      // 尝试上传头像
      tryUploadAvatar(avatarUrl, loginParams, openid) {
        // 先尝试直接传递URL
        loginParams.avatar = avatarUrl;
        this.finishWechatLogin(loginParams);
      },
      
      // 完成微信登录过程
      finishWechatLogin(params) {
        this.$post(
          '~/api/user/open_id_login?',
          params,
          (res) => {
            if (res.result && res.result.obj) {
              let user = res.result.obj;
              let isNewUser = res.result.is_new_user;
              
              if(this.allow_user.includes(user.user_group)){
                // 缓存token
                this.$u.vuex('token', user.token);
                // 存储用户信息
                this.$u.vuex('userInfo', user);
                // 设置权限集
                this.$u.vuex('userGroup', user.user_group);
                // 前往首页
                uni.switchTab({
                  url: '/pages/index/index',
                });
                // 显示不同的提示信息
                if (isNewUser) {
                  this.$toast("微信账号注册成功", 'success');
                } else {
                  this.$toast("登录成功", 'success');
                }
                console.log('---登录成功---');
              } else {
                this.$toast("您的账号不支持在用户端登录！", 'error');
              }
            } else if (res.error) {
              this.$toast(res.error.message, 'error');
            }
          }
        );
      },
      // #endif
    },
    onBackPress() {
      var bl = false;
      var user_id = this.user.user_id;
      if (user_id == null || user_id < 1) {
        // this.$nav('/pages/index/index');
        bl = true;
      }
      return false;
    },
  };
</script>

<style lang="scss" scoped>
  @import '@/styles/pagesB/index.scss';
</style>
